﻿using AutoMapper;
using Frame.Core.Attribute;
using Frame.Core.Auth;
using Frame.Core.Common.Auth;
using Frame.Core.Common.Common;
using Frame.Core.IServices.Admin;
using Frame.Core.Models;
using Frame.Core.Models.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Frame.Core.Controllers
{
    [Authorize]
    public class AdminController : BaseController
    {
        readonly IWebHostEnvironment _env;
        readonly IMapper _mapper;
        readonly IUser _user;
        readonly IOnlineService _onlineService;
        readonly IPermissionHandler _permissionHandler;
        readonly IUserService _userService;
        readonly ITitleService _titleService;
        readonly IRoleService _roleService;
        readonly IPowerService _powerService;
        readonly IMenuService _menuService;
        readonly IDeptService _deptService;
        readonly IBasicDataService _titleUserService;
        readonly IRoleUserService _roleUserService;
        readonly IRolePowerService _rolePowerService;
        readonly IFreeSql _freeSql;

        public AdminController(IWebHostEnvironment env, IMapper mapper, IUser user, IOnlineService onlineService, IPermissionHandler permissionHandler, IUserService userService, ITitleService titleService
            , IRoleService roleService, IPowerService powerService, IMenuService menuService, IDeptService deptService, IBasicDataService titleUserService, IRoleUserService roleUserService
            , IRolePowerService rolePowerService, IFreeSql freeSql)
        {
            _env = env;
            _user = user;
            base.onlineService = onlineService;
            _onlineService = onlineService;
            _permissionHandler = permissionHandler;
            _userService = userService;
            _titleService = titleService;
            _roleService = roleService;
            _powerService = powerService;
            _menuService = menuService;
            _deptService = deptService;
            _titleUserService = titleUserService;
            _roleUserService = roleUserService;
            _rolePowerService = rolePowerService;
            _mapper = mapper;
            _freeSql = freeSql;
        }

        #region UserList
        [CheckPower(Name = "CoreUserView")]
        public async Task<IActionResult> UserList()
        {
            ViewBag.CoreUserNew = await _permissionHandler.CheckPower("CoreUserNew");
            ViewBag.CoreUserEdit = await _permissionHandler.CheckPower("CoreUserEdit");
            ViewBag.CoreUserDelete = await _permissionHandler.CheckPower("CoreUserDelete");
            ViewBag.CoreUserChangePassword = await _permissionHandler.CheckPower("CoreUserChangePassword");

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetListJSON(int page, int limit, string key, string field, string order)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Users>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<Users, bool>> whereExpression = a => a.Name.Contains(key) && a.Name != "admin";
            var list = await _userService.GetUserList(pagingInfo, whereExpression);
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = list });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UserEnabledChange(int userID, bool userEnable)
        {
            // 在操作之前进行权限检查
            if (!await _permissionHandler.CheckPower("CoreUserEdit"))
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "无权限！" });
            }

            // 执行数据库操作
            if (userEnable)
            {
                await _userService.EditSingeColumnAsync(u => u.Enabled == true, s => s.ID == userID);
            }
            else
            {
                await _userService.EditSingeColumnAsync(u => u.Enabled == false, s => s.ID == userID);
            }
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region UserNew
        [CheckPower(Name = "CoreUserNew")]
        public async Task<IActionResult> UserNew()
        {
            ViewBag.ddlTaskRoleData = await _freeSql.Select<TypeEnum>().Where(a=>a.TypeKey== "TaskRole" && a.Status==true).ToListAsync();
            return View();
        }

        public async Task<IActionResult> GetDeptListJson()
        {
            List<Depts> list = await _deptService.GetDeptsAsync();
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "成功诺", data = list });
        }


        public async Task<IActionResult> SelectTitleData()
        {
            List<FormSelectsResult> list = new List<FormSelectsResult>();
            List<Titles> list1 = await _titleService.GetListAsync(null);
            foreach (Titles item in list1)
            {
                list.Add(new FormSelectsResult { name = item.Name, value = item.ID.ToString() });
            }
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "hhh", data = list });
        }

        public async Task<IActionResult> SelectRoleData()
        {
            List<FormSelectsResult> list = new List<FormSelectsResult>();
            List<Roles> list1 = await _roleService.GetListAsync(null);
            foreach (Roles item in list1)
            {
                list.Add(new FormSelectsResult { name = item.Name, value = item.ID.ToString() });
            }
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "hhh", data = list });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreUserNew")]
        public async Task<IActionResult> UserNew_btnSaveClose_Click(string userJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(userJson);
            Users user = new Users();

            //需要二次处理的数据，必须先取处理，不然会报错
            string strPwd = DynamicObject.Password;
            string strEnabled = DynamicObject.Enabled;
            string strTitles = DynamicObject.Titles;
            string strRoles = DynamicObject.Roles;
            string strSupplierId= DynamicObject.SupplierId;

            //二次处理
            int[] arrTitles = Array.ConvertAll(strTitles.Split(','), int.Parse);
            int[] arrRoles = Array.ConvertAll(strRoles.Split(','), int.Parse);

            //封装对象
            user.Name = DynamicObject.Name;
            user.ChineseName = DynamicObject.ChineseName;
            user.Password = PasswordUtil.CreateDbPassword(strPwd);
            user.Email = DynamicObject.Email;
            user.Address = DynamicObject.Address;
            user.CellPhone = DynamicObject.CellPhone;
            user.Gender = DynamicObject.Gender;
            user.DeptID = DynamicObject.DeptID;
            user.TaskRoleId = DynamicObject.TaskRoleId;
            user.Enabled = true;
            user.Remark = DynamicObject.Remark;
            user.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            Users _user = await _userService.GetAsync(s => s.Name == user.Name);
            if (_user != null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "用户 " + user.Name + " 已经存在！" });
            }
            try
            {
                await _userService.AddUserAsync(user, arrRoles, arrTitles);

                return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = ex.Message });
            }
        }


        #endregion

        #region UserEdit
        [CheckPower(Name = "CoreUserEdit")]
        public async Task<IActionResult> UserEdit(int userID)
        {
            ViewBag.ddlTaskRoleData = await _freeSql.Select<TypeEnum>().Where(a => a.TypeKey == "TaskRole" && a.Status == true).ToListAsync();
            ViewBag.User = await _userService.GetUserFirst(s => s.ID == userID);

            // 用户所属角色
            int[] roles = (await _roleUserService.GetListAsync(s => s.UserID == userID)).Select(s => s.RoleID).ToArray();
            ViewBag.selectRoleIDs= string.Join(",",roles);
            // 用户拥有职称
            int[] titles = (await _titleUserService.GetListAsync(s => s.UserID == userID)).Select(s => s.TitleID).ToArray();
            ViewBag.selectTitleIDs = string.Join(",", titles);

            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreUserEdit")]
        public async Task<IActionResult> UserEdit_btnSaveClose_Click(string userJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(userJson);
            string user_name = _user.ChineseName;
            Users user = new Users();

            //需要二次处理的数据，必须先取处理，不然会报错
            string strEnabled = DynamicObject.Enabled;
            string strTitles = DynamicObject.Titles;
            string strRoles = DynamicObject.Roles;
            string strSupplierId = DynamicObject.SupplierId;

            //二次处理
            int[] arrTitles = Array.ConvertAll(strTitles.Split(','), int.Parse);
            int[] arrRoles = Array.ConvertAll(strRoles.Split(','), int.Parse);

            if (!string.IsNullOrEmpty(strEnabled))
            {
                user.Enabled = strEnabled == "on" ? true : false;
            }

            //封装对象
            user.ID = DynamicObject.ID;
            user.ChineseName = DynamicObject.ChineseName;
            user.Email = DynamicObject.Email;
            user.Address = DynamicObject.Address;
            user.TaskRoleId = DynamicObject.TaskRoleId;
            user.CellPhone = DynamicObject.CellPhone;
            user.Gender = DynamicObject.Gender;
            user.DeptID = DynamicObject.DeptID;
            user.Remark = DynamicObject.Remark;
            user.LastLoginTime = DateTime.Now;
            
            try
            {
                await _userService.EditUserAsync(user, arrRoles, arrTitles);
                return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
            }
            catch (Exception ex)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = ex.Message });
            }

        }

        #endregion

        #region UserChangePassword

        [CheckPower(Name = "CoreUserChangePassword")]
        public IActionResult UserChangePassword()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreUserChangePassword")]
        public async Task<IActionResult> UserChangePasswordUpdate(int userID, string password)
        {
            // 检查当前密码是否正确
            Users user = await _userService.GetAsync(a => a.ID == userID);

            if (user != null)
            {
                user.Password = PasswordUtil.CreateDbPassword(password);
                await _userService.EditAsync(user);
                return Json(new AjaxResult { codeIndex = 1, msg = "修改密码成功！" });
            }
            else
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "未知错误，请联系系统管理员！" });
            }
        }

        #endregion ChangePassword


        #region Titie
        [CheckPower(Name = "CoreTitleView")]
        public async Task<IActionResult> Title()
        {
            ViewBag.CoreTitleNew = await _permissionHandler.CheckPower("CoreTitleNew");
            ViewBag.CoreTitleEdit = await _permissionHandler.CheckPower("CoreTitleEdit");
            ViewBag.CoreTitleDelete = await _permissionHandler.CheckPower("CoreTitleDelete");



            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetTitleListJSON(int page, int limit, string key, string field, string order)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Titles>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<Titles, bool>> whereExpression = a => a.Name.Contains(key);
            await _titleService.QueryAsync(whereExpression, pagingInfo);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = pagingInfo.List });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreTitleDelete")]
        public async Task<IActionResult> DeleteTitle(int titleID)
        {
            long titleCount = await _titleService.GetTitleUsersCountById(titleID);
            if (titleCount > 0)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "删除失败！需要先清空属于此职称的用户！" });
            }
            await _titleService.DelAsync(d => d.ID == titleID);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region TitleNew
        [CheckPower(Name = "CoreTitleNew")]
        public IActionResult TitleNew()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreTitleNew")]
        public async Task<IActionResult> TitleNew_btnSaveClose_Click(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Titles title = new Titles
            {
                //封装对象
                Name = DynamicObject.Name,
                Remark = DynamicObject.Remark
            };
            var sTitle = await _titleService.GetAsync(s => s.Name == title.Name);
            if (sTitle !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "职称已经存在！" });
            }
            await _titleService.AddAsync(title);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });

        }
        #endregion

        #region TitleEdit
        [CheckPower(Name = "CoreTitleEdit")]
        public async Task<IActionResult> TitleEdit(int id)
        {
            ViewBag.Title = await _titleService.GetAsync(s => s.ID == id);
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreTitleEdit")]
        public async Task<IActionResult> TitleEdit_Update(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Titles title = new Titles
            {
                //封装对象
                ID = DynamicObject.ID,
                Name = DynamicObject.Name,
                Remark = DynamicObject.Remark
            };
            var sTitle = await _titleService.GetAsync(s => s.Name == title.Name && s.ID != title.ID);
            if (sTitle !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "职称已经存在！" });
            }
            else
            {
                sTitle = await _titleService.GetAsync(s => s.ID == title.ID);
            }
            await _titleService.AttachEditAsync(sTitle, title);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });

        }
        #endregion

        #region TitleUser
        [CheckPower(Name = "CoreTitleUserView")]
        public async Task<IActionResult> TitleUser()
        {
            ViewBag.CoreTitleUserNew = await _permissionHandler.CheckPower("CoreTitleUserNew");
            ViewBag.CoreTitleUserDelete = await _permissionHandler.CheckPower("CoreTitleUserDelete");
            return View();
        }


        #region 查询职称用户列表
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetTitleUserJSON(int page, int limit, string key, string field, string order, int titleID)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<TitleUsers>
            {
                PageKey = a => a.TitleID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<TitleUsers, bool>> whereExpression = a => a.Users.Name.Contains(key) && a.TitleID == titleID;
            await _titleUserService.QueryAsync(whereExpression, pagingInfo);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = pagingInfo.List });
        }
        #endregion

        #region 删除职称用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreTitleUserDelete")]
        public async Task<IActionResult> DeleteTitleUserId(List<int> deletedUserIDs, int titleID)
        {
            // 执行数据库操作
            await _titleUserService.DelAsync(d => d.TitleID == titleID && deletedUserIDs.Contains(d.UserID));
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #endregion TitleUser

        #region TitleUserNew
        [CheckPower(Name = "CoreTitleUserNew")]
        public IActionResult TitleUserNew()
        {
            return View();
        }

        #region 添加职称用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreTitleUserNew")]
        public async Task<IActionResult> SelectedTitleUserId(int[] selectUserIDs, int titleID)
        {
            var list = selectUserIDs.Select(a => new TitleUsers { UserID = a, TitleID = titleID }).ToArray();
            await _titleUserService.AddAsync(list);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region 职称可选用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetTitleOptionalUserListJSON(int page, int limit, string key, string field, string order, int titleID)
        {
            Expression<Func<Users, bool>> whereExpression=null;

            if (!string.IsNullOrWhiteSpace(key))
            {
                whereExpression= whereExpression.And(a => a.Name.Contains(key));
            }

            var titleUsers = await _titleUserService.GetListAsync(s => s.TitleID == titleID);
            var titleUsersUserIdArr = titleUsers.Select(s => s.UserID).ToArray();

            if (titleUsersUserIdArr.Length!=0)
            {
                whereExpression = whereExpression.And(a => !titleUsersUserIdArr.Contains(a.ID));
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Users>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };

            var list = await _userService.GetUserList(pagingInfo, whereExpression);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = list });
        }
        #endregion

        #endregion


        #region Role
        [CheckPower(Name = "CoreRoleView")]
        public async Task<IActionResult> Role()
        {
            ViewBag.CoreRoleNew = await _permissionHandler.CheckPower("CoreRoleNew");
            ViewBag.CoreRoleEdit = await _permissionHandler.CheckPower("CoreRoleEdit");
            ViewBag.CoreRoleDelete = await _permissionHandler.CheckPower("CoreRoleDelete");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetRoleListJSON(int page, int limit, string key, string field, string order)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Roles>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<Roles, bool>> whereExpression = a => a.Name.Contains(key);
            await _roleService.QueryAsync(whereExpression, pagingInfo);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = pagingInfo.List });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreRoleDelete")]
        public async Task<IActionResult> DeleteRole(int roleID)
        {
            long roleUsersCount = await _roleService.GetRoleUsersCountById(roleID);
            if (roleUsersCount > 0)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "删除失败！需要先清空属于此角色的用户！" });
            }
            await _roleService.DelAsync(d => d.ID == roleID);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region RoleNew
        [CheckPower(Name = "CoreRoleNew")]
        public IActionResult RoleNew()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreRoleNew")]
        public async Task<IActionResult> RoleNew_btnSaveClose_Click(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Roles role = new Roles
            {
                //封装对象
                Name = DynamicObject.Name,
                Remark = DynamicObject.Remark
            };
            var sRole = await _roleService.GetAsync(s => s.Name == role.Name);
            if (sRole !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "角色已经存在！" });
            }
            await _roleService.AddAsync(role);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }
        #endregion

        #region RoleEdit
        [CheckPower(Name = "CoreRoleEdit")]
        public async Task<IActionResult> RoleEdit(int id)
        {
            ViewBag.Role = await _roleService.GetAsync(s => s.ID == id);
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreRoleEdit")]
        public async Task<IActionResult> RoleEdit_Update(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Roles role = new Roles
            {

                //封装对象
                ID = DynamicObject.ID,
                Name = DynamicObject.Name,
                Remark = DynamicObject.Remark
            };
            var sRole = await _roleService.GetAsync(s => s.Name == role.Name && s.ID != role.ID);
            if (sRole !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "角色已经存在！" });
            }
            else
            {
                sRole = await _roleService.GetAsync(s => s.ID == role.ID);
            }
            await _roleService.AttachEditAsync(sRole, role);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region RoleUser
        [CheckPower(Name = "CoreRoleUserView")]
        public async Task<IActionResult> RoleUser()
        {
            ViewBag.CoreRoleUserNew = await _permissionHandler.CheckPower("CoreRoleUserNew");
            ViewBag.CoreRoleUserDelete = await _permissionHandler.CheckPower("CoreRoleUserDelete");
            return View();
        }

        #region 查询角色用户列表

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetRoleUserJSON(int page, int limit, string key, string field, string order, int roleID)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<RoleUsers>
            {
                PageKey = a => a.RoleID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<RoleUsers, bool>> whereExpression = a => a.Users.Name.Contains(key) && a.Users.Name != "admin" && a.RoleID == roleID;
            await _roleUserService.QueryAsync(whereExpression, pagingInfo);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = pagingInfo.List });
        }
        #endregion

        #region 删除角色用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreRoleUserDelete")]
        public async Task<IActionResult> DeleteRoleUserId(List<int> deletedUserIDs, int roleID)
        {
            await _roleUserService.DelAsync(d => d.RoleID == roleID && deletedUserIDs.Contains(d.UserID));
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #endregion TitleUser

        #region RoleUserNew
        [CheckPower(Name = "CoreRoleUserNew")]
        public IActionResult RoleUserNew()
        {
            return View();
        }

        #region 添加角色用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreRoleUserNew")]
        public async Task<IActionResult> SelectedRoleUserId(int[] selectUserIDs, int roleID)
        {
            var list = selectUserIDs.Select(a => new RoleUsers { UserID = a, RoleID = roleID }).ToArray();
            await _roleUserService.AddAsync(list);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region 职称可选用户

        public async Task<IActionResult> GetRoleOptionalUserListJSON(int page, int limit, string key, string field, string order, int roleID)
        {

            Expression<Func<Users, bool>> whereExpression = a=> a.Name != "admin";

            if (!string.IsNullOrWhiteSpace(key))
            {
                whereExpression = whereExpression.And(a => a.Name.Contains(key));
            }

            var roleUsers = await _roleUserService.GetListAsync(s => s.RoleID == roleID);
            var roleUsersUserIdArr = roleUsers.Select(s => s.UserID).ToArray();

            if (roleUsersUserIdArr.Length != 0)
            {
                whereExpression = whereExpression.And(a => !roleUsersUserIdArr.Contains(a.ID));
            }

            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Users>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };

            var list = await _userService.GetUserList(pagingInfo, whereExpression);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = list });
        }
        #endregion

        #endregion


        #region Power
        [CheckPower(Name = "CorePowerView")]
        public async Task<IActionResult> Power()
        {
            ViewBag.CorePowerNew = await _permissionHandler.CheckPower("CorePowerNew");
            ViewBag.CorePowerEdit = await _permissionHandler.CheckPower("CorePowerEdit");
            ViewBag.CorePowerDelete = await _permissionHandler.CheckPower("CorePowerDelete");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetPowerListJSON(int page, int limit, string key, string field, string order)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Powers>
            {
                PageKey = a => a.ID,
                SortField = field??"Remark",
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<Powers, bool>> whereExpression = a => a.Name.Contains(key) || a.Menus.Name.Contains(key) || a.Title.Contains(key);
            await _powerService.QueryAsync(whereExpression, pagingInfo);
            //处理dto映射
            var list = _mapper.Map<List<PowersDto>>(pagingInfo.List);
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = list });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CorePowerDelete")]
        public async Task<IActionResult> DeletePower(int powerID)
        {
            long rolePowersCount = await _powerService.GetRolePowersCountById(powerID);
            if (rolePowersCount > 0)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "删除失败！需要先清空使用此权限的角色！" });
            }
            await _powerService.DelAsync(d => d.ID == powerID);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region PowerNew

        [CheckPower(Name = "CorePowerNew")]
        public IActionResult PowerNew()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CorePowerNew")]
        public async Task<IActionResult> PowerNew_btnSaveClose_Click(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Powers power = new Powers
            {
                //封装对象
                Name = DynamicObject.Name,
                MenusId = DynamicObject.MenusId,
                Title = DynamicObject.Title,
                Remark = DynamicObject.Remark
            };
            var sRole = await _powerService.GetAsync(s => s.Name == power.Name);
            if (sRole !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "权限名称已经存在！" });
            }
            await _powerService.AddAsync(power);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }
        #endregion

        #region PowerEdit
        [CheckPower(Name = "CorePowerEdit")]
        public async Task<IActionResult> PowerEdit(int id)
        {
            ViewBag.Power = await _powerService.GetAsync(s => s.ID == id);
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CorePowerEdit")]
        public async Task<IActionResult> PowerEdit_Update(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Powers power = new Powers
            {

                //封装对象
                ID = DynamicObject.ID,
                Name = DynamicObject.Name,
                MenusId = DynamicObject.MenusId,
                Title = DynamicObject.Title,
                Remark = DynamicObject.Remark
            };
            var sPower = await _powerService.GetAsync(s => s.Name == power.Name && s.ID != power.ID && s.MenusId == power.MenusId);
            if (sPower !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "权限名称+权限分组已经存在！" });
            }
            else
            {
                sPower = await _powerService.GetAsync(s => s.ID == power.ID);
            }
            await _powerService.AttachEditAsync(sPower, power);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region RolePower
        [CheckPower(Name = "CoreRolePowerView")]
        public async Task<IActionResult> RolePower()
        {
            ViewBag.CoreRolePowerEdit = await _permissionHandler.CheckPower("CoreRolePowerEdit");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetRolePowerJSON(int roleID)
        {
            //获取对应的角色权限
            string RolePowerIds = string.Empty;
            if (roleID != 0)
            {
                var rolePowerList = await _rolePowerService.GetListAsync(s => s.RoleID == roleID);
                RolePowerIds = string.Join(",", rolePowerList.Select(s => s.PowerID).ToArray());
            }
            List<GroupPowerViewModel> list = await RolePower_GetData();

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = RolePowerIds, count = 1000, data = list });

        }
        private async Task<List<GroupPowerViewModel>> RolePower_GetData()
        {
            var menus = await _menuService.GetMenusAsync();
            List<GroupPowerViewModel> GroupPowerList = new List<GroupPowerViewModel>();
            var list = await _powerService.GetListAsync(null);
            foreach (var menu in menus)
            {
                GroupPowerViewModel GroupPower = new GroupPowerViewModel
                {
                    GroupName = menu.Name,
                    ID = menu.ID,
                    ParentID = menu.ParentID
                };
                //查询菜单id对应的权限列表
                var powers = list.Where(u => u.MenusId == menu.ID).OrderBy(b=>b.Remark).ToList();
                GroupPower.Powers = powers;

                GroupPowerList.Add(GroupPower);
            }

            return GroupPowerList;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreRolePowerEdit")]
        public async Task<IActionResult> EditRolePower(int roleID, int[] powers)
        {
            try
            {
                await _rolePowerService.SaveRolePowerAsync(roleID, powers);
            }
            catch (Exception ex)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = ex.Message });
            }
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion


        #region Menu 
        [CheckPower(Name = "CoreMenuView")]
        public async Task<IActionResult> Menu()
        {
            ViewBag.CoreMenuNew = await _permissionHandler.CheckPower("CoreMenuNew");
            ViewBag.CoreMenuEdit = await _permissionHandler.CheckPower("CoreMenuEdit");
            ViewBag.CoreMenuDelete = await _permissionHandler.CheckPower("CoreMenuDelete");
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> PostMenuListJson()
        {
            List<Menus> list = await _menuService.GetMenusAsync();
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = 0, data = list });

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreMenuDelete")]
        public async Task<IActionResult> DeleteMenu(int menuID)
        {
            long menuParentIDCount = await _menuService.GetMenuParentIDCountById(menuID);
            if (menuParentIDCount > 0)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "删除失败！请先删除子菜单！" });
            }

            long powerMenusIdCount = await _menuService.GetPowerMenusIdCountById(menuID);
            if (powerMenusIdCount > 0)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "删除失败！请先解除权限的引用！" });
            }

            await _menuService.DelAsync(d => d.ID == menuID);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region MenuNew
        [CheckPower(Name = "CoreMenuNew")]
        public IActionResult MenuNew()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> PostNewMenuListJson()
        {
            List<Menus> list = await _menuService.GetMenusAsync();
            list.Insert(0, new Menus { ID = -1, ParentID = 0, Name = "--根节点--" });//添加根节点
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "成功诺", data = list });

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreMenuNew")]
        public async Task<IActionResult> MenuNew_btnSaveClose_Click(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);
            string viewPowerName = DynamicObject.ViewPowerName;
            Menus menu = new Menus
            {
                //封装对象
                Name = DynamicObject.Name,
                ParentID = DynamicObject.ParentID,
                SortIndex = DynamicObject.SortIndex,
                Remark = DynamicObject.Remark,
                ImageUrl = DynamicObject.ImageUrl,
                NavigateUrl = DynamicObject.NavigateUrl
            };

            var sMenu = await _menuService.GetAsync(s => s.Name == menu.Name && s.ParentID == menu.ParentID);
            if (sMenu !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "父菜单已经存在此菜单名！" });
            }

            // 下拉列表的顶级节点值为-1
            if (menu.ParentID == -1)
            {
                menu.ParentID = 0;
            }
            if (string.IsNullOrEmpty(viewPowerName))
            {
                menu.ViewPowerID = null;
            }
            else
            {
                var power = await _powerService.GetAsync(s => s.Name == viewPowerName);
                if (power !=null)
                {
                    menu.ViewPowerID = power.ID;
                }
            }
            await _menuService.AddAsync(menu);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region MenuEdit
        [CheckPower(Name = "CoreMenuEdit")]
        public async Task<IActionResult> MenuEdit(int id)
        {
            ViewBag.Menu = await _menuService.GetLeftJoinAsync(l => l.ViewPowerID == l.Powers.ID, s => s.ID == id);
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreMenuEdit")]
        public async Task<IActionResult> MenuEdit_Update(string ajaxJson)
        {

            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);
            string viewPowerName = DynamicObject.ViewPowerName;
            Menus menu = new Menus
            {
                //封装对象
                Name = DynamicObject.Name,
                ParentID = DynamicObject.ParentID,
                SortIndex = DynamicObject.SortIndex,
                Remark = DynamicObject.Remark,
                ID = DynamicObject.ID,
                ImageUrl = DynamicObject.ImageUrl,
                NavigateUrl = DynamicObject.NavigateUrl
            };

            // 下拉列表的顶级节点值为-1
            if (menu.ParentID == -1)
            {
                menu.ParentID = 0;
            }
            if (string.IsNullOrEmpty(viewPowerName))
            {
                menu.ViewPowerID = null;
            }
            else
            {
                var power = await _powerService.GetAsync(s => s.Name == viewPowerName);
                if (power !=null)
                {
                    menu.ViewPowerID = power.ID;
                }
            }

            var sMenu = await _menuService.GetAsync(s => s.Name == menu.Name && s.ParentID == menu.ParentID && s.ID != menu.ID);
            if (sMenu !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "父菜单已经存在此菜单名！" });
            }
            else
            {
                sMenu = await _menuService.GetAsync(s => s.ID == menu.ID);
            }
            await _menuService.AttachEditAsync(sMenu, menu);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion


        #region Dept
        [CheckPower(Name = "CoreDeptView")]
        public async Task<IActionResult> Dept()
        {
            ViewBag.CoreDeptNew = await _permissionHandler.CheckPower("CoreDeptNew");
            ViewBag.CoreDeptEdit = await _permissionHandler.CheckPower("CoreDeptEdit");
            ViewBag.CoreDeptDelete = await _permissionHandler.CheckPower("CoreDeptDelete");

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> PostDeptListJson()
        {
            List<Depts> list = await _deptService.GetDeptsAsync();
            list[0].lay_is_radio = true;//默认选中第一行，treeGrid选中用
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = 0, data = list });

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreDeptDelete")]
        public async Task<IActionResult> DeleteDept(int deptID)
        {
            long deptUsersCount = await _deptService.GetDeptUsersCountById(deptID);
            if (deptUsersCount > 0)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "删除失败！需要先清空属于此部门的用户！" });
            }

            long deptParentIDCoun = await _deptService.GetDeptParentIDCountById(deptID);
            if (deptParentIDCoun > 0)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "删除失败！请先删除子部门！" });

            }

            await _deptService.DelAsync(d => d.ID == deptID);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }
        #endregion Dept

        #region DeptNew
        [CheckPower(Name = "CoreDeptNew")]
        public IActionResult DeptNew()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> PostNewDeptListJson()
        {
            List<Depts> list = await _deptService.GetDeptsAsync();
            list.Insert(0, new Depts { ID = -1, ParentID = 0, Name = "--根节点--" });//添加根节点
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "成功诺", data = list });

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreDeptNew")]
        public async Task<IActionResult> DeptNew_btnSaveClose_Click(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Depts dept = new Depts
            {
                //封装对象
                Name = DynamicObject.Name,
                ParentID = DynamicObject.ParentID,
                SortIndex = DynamicObject.SortIndex,
                Remark = DynamicObject.Remark
            };

            // 下拉列表的顶级节点值为-1
            if (dept.ParentID == -1)
            {
                dept.ParentID = 0;
            }
            var sDept = await _deptService.GetAsync(s => s.Name == dept.Name && s.ParentID == dept.ParentID);
            if (sDept !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "父部门已经存在此部门名！" });
            }
            await _deptService.AddAsync(dept);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region DeptEdit
        [CheckPower(Name = "CoreDeptEdit")]
        public async Task<IActionResult> DeptEdit(int id)
        {
            ViewBag.Dept = await _deptService.GetAsync(s => s.ID == id);
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreDeptEdit")]
        public async Task<IActionResult> DeptEdit_Update(string ajaxJson)
        {
            //json字符串转动态对象
            var DynamicObject = JsonConvert.DeserializeObject<dynamic>(ajaxJson);

            Depts dept = new Depts
            {
                //封装对象
                ID = DynamicObject.ID,
                Name = DynamicObject.Name,
                ParentID = DynamicObject.ParentID,
                SortIndex = DynamicObject.SortIndex,
                Remark = DynamicObject.Remark
            };

            // 下拉列表的顶级节点值为-1
            if (dept.ParentID == -1)
            {
                dept.ParentID = 0;
            }
            var sDept = await _deptService.GetAsync(s => s.Name == dept.Name && s.ParentID == dept.ParentID && s.ID != dept.ID);
            if (sDept !=null)
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "父部门已经存在此部门名！" });
            }
            else
            {
                sDept = await _deptService.GetAsync(s => s.ID == dept.ID);
            }
            await _deptService.AttachEditAsync(sDept, dept);
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });

        }

        #endregion

        #region DeptUser
        [CheckPower(Name = "CoreDeptUserView")]
        public async Task<IActionResult> DeptUser()
        {
            ViewBag.CoreDeptUserNew = await _permissionHandler.CheckPower("CoreDeptUserNew");
            ViewBag.CoreDeptUserDelete = await _permissionHandler.CheckPower("CoreDeptUserDelete");
            return View();
        }

        #region 删除职称用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreDeptUserDelete")]
        public async Task<IActionResult> DeleteDeptUserId(List<int> deletedUserIDs)
        {
            await _userService.EditSingeColumnAsync(u => u.DeptID == null, d => deletedUserIDs.Contains(d.ID));
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region 查询部门用户列表
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetDeptUserJSON(int page, int limit, string key, string field, string order, int deptID)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Users>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<Users, bool>> whereExpression = a => a.Name.Contains(key) && a.Name != "admin" && a.DeptID == deptID;
            var list = await _userService.GetUserList(pagingInfo, whereExpression);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = list }); ;
        }
        #endregion
        #endregion

        #region DeptUserNew
        [CheckPower(Name = "CoreDeptUserNew")]
        public IActionResult DeptUserNew()
        {
            return View();
        }

        #region 添加部门用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreDeptUserNew")]
        public async Task<IActionResult> SelectedDeptUserId(int[] selectUserIDs, int deptID)
        {
            await _userService.EditSingeColumnAsync(u => u.DeptID == deptID, d => selectUserIDs.Contains(d.ID));
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        #endregion

        #region 部门可选用户
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetDeptOptionalUserListJSON(int page, int limit, string key, string field, string order)
        {

            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Users>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };

            Expression<Func<Users, bool>> whereExpression = a => a.Name.Contains(key) && a.Name != "admin" && a.DeptID == null;

            var list = await _userService.GetUserList(pagingInfo, whereExpression);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = list });
        }
        #endregion

        #endregion


        #region ChangePassword

        // GET: Admin/ChangePassword
        public IActionResult ChangePassword()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ChangePassword_btnSave_OnClick(string oldPassword, string password)
        {
            // 检查当前密码是否正确
            Users user = await _userService.GetAsync(a => a.ID == _user.Id);
            if (user != null)
            {
                if (!PasswordUtil.ComparePasswords(user.Password, oldPassword))
                {
                    return Json(new AjaxResult { codeIndex = 0, msg = "当前密码不正确！" });
                }
                else
                {
                    user.Password = PasswordUtil.CreateDbPassword(password);
                    await _userService.EditAsync(user);

                    return Json(new AjaxResult { codeIndex = 1, msg = "修改密码成功！" });
                }
            }
            else
            {
                return Json(new AjaxResult { codeIndex = 0, msg = "未知错误，请联系系统管理员！" });
            }
        }

        #endregion ChangePassword

        #region Online

        [CheckPower(Name = "CoreOnlineView")]
        public IActionResult Online()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> GetOnlineListJSON(int page, int limit, string field, string order, string key = "")
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }
            order ??= "asc";
            var pagingInfo = new PagingInfoViewModel<Onlines>
            {
                PageKey = a => a.ID,
                SortField = field,
                Descending = order == "asc",
                PageIndex = page,
                PageSize = limit
            };
            Expression<Func<Onlines, bool>> whereExpression = a => a.Users.Name.Contains(key) || a.Users.ChineseName.Contains(key);
            await _onlineService.QueryAsync(whereExpression, pagingInfo);
            //处理dto映射
            var list = _mapper.Map<List<OnlinesDto>>(pagingInfo.List);
            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = pagingInfo.Count, data = list });
        }

        #endregion Online


        #region 调试工具
        public IActionResult DebugSqlView()
        {
            return View();
        }

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public IActionResult DebugSqlResult(string sql)
        //{
        //    System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        //    stopwatch.Start();
        //    int count = _adminBaseDataServices.ResultFirstOrDefault<int>(sql, null);
        //    stopwatch.Stop();
        //    return Json(new AjaxResult { codeIndex = 1, msg = stopwatch.Elapsed.TotalMilliseconds.ToString(), data = count });

        //}

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public IActionResult DebugSqlResultTime(string sql, int index, int page)
        //{
        //    System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
        //    stopwatch.Start();
        //    var list = _adminBaseDataServices.ResultDynamicPageList(sql, page, index);
        //    stopwatch.Stop();

        //    return Json(new AjaxResult { codeIndex = 1, msg = stopwatch.Elapsed.TotalMilliseconds.ToString() });
        //}

        #endregion

        #region 文件上传列表
        [CheckPower(Name = "CoreUploadView")]
        public async Task<IActionResult> UploadFileList()
        {
            ViewBag.CoreUploadEdit = await _permissionHandler.CheckPower("CoreUploadEdit");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult PostFileListJson()
        {
            List<FileClass> list = new List<FileClass>();
            string strRootpath = _env.ContentRootPath;
            string server_strFilePath = strRootpath + "\\upload";

            // 生成树
            ResolveMenuTree(server_strFilePath, list);

            return Json(new LayuiTableDataAjaxResult { code = 0, msg = "", count = 0, data = list });
        }
        private int StaticIndex = 0;
        private int ParentIndex;
        private void ResolveMenuTree(string path, List<FileClass> list)
        {
            //获得当前这一目录下所有文件夹的路径
            string[] dics = Directory.GetDirectories(path);
            for (int i = 0; i < dics.Length; i++)
            {
                StaticIndex++;
                ParentIndex = StaticIndex;
                //从文件夹的全路径中截取出文件夹的名字
                string dicName = Path.GetFileNameWithoutExtension(dics[i]);

                string dicPath = Path.GetFullPath(dics[i]);
                FileClass node = new FileClass();
                list.Add(node);

                node.ID = StaticIndex;
                node.FileName = dicName;
                node.FilePath = "";
                node.ParentID = 0;
                node.FileSize = "";
                node.FileDate = null;
                //node.lay_icon_open = "/layuiadmin/layui_ext/img/door_in.png";
                //node.lay_icon_close = "/layuiadmin/layui_ext/img/door_out.png";

                //添加文件夹下的文件
                string[] childFile = Directory.GetFiles(dics[i]);
                for (int j = 0; j < childFile.Length; j++)
                {
                    StaticIndex++;
                    //文件名称
                    string chilName = Path.GetFileName(childFile[j]);


                    //文件大小
                    FileInfo fileInfo = new FileInfo(dicPath + "\\" + chilName);
                    FileClass nodeFile = new FileClass()
                    {
                        ID = StaticIndex,
                        FileName = chilName,

                        FilePath = childFile[j].Substring(childFile[j].LastIndexOf("upload")),
                        //FilePath = @childFile[j],
                        ParentID = ParentIndex,
                        FileDate = fileInfo.CreationTime,
                        FileSize = $"{System.Math.Ceiling(fileInfo.Length / 1024.0 / 1024.0)}MB",
                        //lay_icon= "/layuiadmin/layui_ext/img/flag_bo.png"

                    };
                    list.Add(nodeFile);
                }
                //获得当前文件夹下所有文件的全路径
                //ResolveMenuTree(dics[i], StaticIndex, list);
            }

        }

        #region 上传多文件
        public IActionResult UploadFiles()
        {

            string server_strFilePath = _env.ContentRootPath + "/upload";
            //获得当前这一目录下所有文件夹的路径
            string[] dics = Directory.GetDirectories(server_strFilePath);
            List<string> list = new List<string>();
            for (int i = 0; i < dics.Length; i++)
            {
                //从文件夹的全路径中截取出文件夹的名字
                list.Add(Path.GetFileNameWithoutExtension(dics[i]));
            }
            ViewBag.Files = list;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CheckPower(Name = "CoreUploadEdit")]
        public async Task<IActionResult> UploadFile(string filePath)
        {
            try
            {
                var file = Request.Form.Files[0]; //获取选中文件  
                //获取服务器路径+文件
                string server_strFilePath = _env.ContentRootPath + "/upload/" + filePath + "/" + file.FileName;

                using (var stream = new FileStream(server_strFilePath, FileMode.Create))
                {

                    await file.CopyToAsync(stream);
                }
            }
            catch (Exception ex)
            {
                return Json(new AjaxResult { code = -1, codeIndex = 1, msg = "错误：" + ex.Message });
            }
            return Json(new AjaxResult { codeIndex = 1, msg = "成功" });
        }

        /// <summary>
        /// 文件流的方式输出        /// </summary>
        /// <returns></returns>
        public IActionResult DownLoad(string file)
        {
            var addrUrl = file;
            var stream = System.IO.File.OpenRead(addrUrl);
            string fileExt = Path.GetExtension(file);
            //获取文件的ContentType
            var provider = new FileExtensionContentTypeProvider();
            var memi = provider.Mappings[fileExt];
            return File(stream, memi, Path.GetFileName(addrUrl));
        }

        [HttpGet]
        public async Task<IActionResult> DownloadFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return NotFound();
            }

            string serverFilePath = _env.ContentRootPath + "//" + filePath;
            string fileName = Path.GetFileName(serverFilePath);
            var memoryStream = new MemoryStream();
            using (var stream = new FileStream(serverFilePath, FileMode.Open))
            {
                await stream.CopyToAsync(memoryStream);
            }
            memoryStream.Seek(0, SeekOrigin.Begin);
            //文件名必须编码，否则会有特殊字符(如中文)无法在此下载。
            string encodeFilename = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.GetEncoding("UTF-8"));
            Response.Headers.Add("Content-Disposition", "attachment; filename=" + encodeFilename);
            return new FileStreamResult(memoryStream, "application/octet-stream");//文件流方式，指定文件流对应的ContenType。
        }
        #endregion

        #endregion

    }
}
